package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParameterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

/**
 * @author MissChen
 * @date 2024年04月02日 10:04
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao= (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao= (ItemDao) ObjectFactory.getObject("itemDao");
    @Override
    public String createOrder(Cart cart, User user) throws UserNotLoginException {
        if(cart==null ||user==null){
            throw new UserNotLoginException("请先登录");
        }
        //保存一条订单与多条明细
        //添加明细时，需要知道当前已经保存的订单的主键值
        // 因此：先添加订单，再添加明细
        // 1.添加订单
        Order order=new Order();
        order.setNo(ParameterUtil.createNo());
        order.setPrice(cart.getPrice());
        order.setUser(user);
        //添加订单并返回主键
        Integer id=orderDao.insertReturnPrimaryKey(order);

        //将返回的主键设置给对应的订单对象
        order.setId(id);

        // 2.添加明细
        // 取出所有需要添加的明细信息
        List<Item> items=cart.getItems();
        //遍历这些明细，每遍历一条明细，添加一条记录
        for(Item item:items){
            //在购物车中的明细信息中，没有对应的订单信息
            //先将对应的订单信息赋值给对应的明细
            item.setOrder(order);
            itemDao.insertItem(item);
        }
        return order.getNo();
    }

    @Override
    public List<Order> findMyOrders(User user) throws UserNotExistException {
        if(user==null){
            throw new UserNotExistException("请先登录");
        }
        List<Order> orders=orderDao.selectByUserId(user.getId());
        return orders;
    }

    @Override
    public Order findOrderDetail(Integer id) throws RequestParameterErrorException {
        if(id==null){
            throw new RequestParameterErrorException("请求参数有误");
        }
        Order order=orderDao.selectById(id);
        return order;
    }
}
